package cn.ixinjiu.libraryMangement.controller.systemAdmin.admin;

import cn.ixinjiu.libraryMangement.dao.IUserInfoDao;
import cn.ixinjiu.libraryMangement.dao.impl.UserInfoDaoImpl;
import cn.ixinjiu.libraryMangement.entity.UserInfo;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by XinChen on 2023-06-10
 *
 * @TODO 用户信息列表
 */
@WebServlet("/adminList")
public class AdminListServlet extends HttpServlet {
    private IUserInfoDao userInfoDao = new UserInfoDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type", "text/html;charset=utf-8");

        List<UserInfo> userList = userInfoDao.userList();
        JSONArray jsonArray = new JSONArray(); // 中转站
        JSONObject jsonObject = new JSONObject(); // 要返回的json对象

        int flag = 0;

        for (UserInfo userInfo : userList) {

            if (userInfo.getRole() == 1) { // 普通管理员
                JSONObject jsonDate = new JSONObject(); // json数据
                jsonDate.put("id", userInfo.getId());
                jsonDate.put("userName",userInfo.getUserName());
                jsonDate.put("password",userInfo.getPassword());
                jsonDate.put("email",userInfo.getEmail());
                jsonDate.put("phoneNumber",userInfo.getPhoneNumber());
                jsonDate.put("role",userInfo.getRole());
                jsonArray.add(jsonDate);
                flag += 1;
            }

        }

        jsonObject.put("code", 0); // 设置状态码，0正常
        jsonObject.put("data", jsonArray.toArray()); // 设置数据
        jsonObject.put("count", flag); // 设置 “共 ？ 条” 数据
        jsonObject.put("msg", "success~"); // 设置提示信息
        // 写入到页面
        PrintWriter out = resp.getWriter();
        out.write(jsonObject.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
